package com.adxon.cookie;

import com.adxon.MsgException;
import com.adxon.data.Asset;
import com.adxon.data.Individual;
import com.adxon.data.Item;
import com.adxon.data.Session;
import com.adxon.data.User;
import com.adxon.servlet.ServletBase;
import com.google.appengine.api.users.UserServiceFactory;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Station extends Kooky{
	private final static String	ATR="s";
	private static boolean		ggl=
			ServletBase.authentication.equalsIgnoreCase("google");

	public static String createLoginURL(String destinationURL){
		return ggl?UserServiceFactory.getUserService().
				createLoginURL(destinationURL):"/system/signin";
	}
	public static String createLogoutURL(String destinationURL){
		return ggl?UserServiceFactory.getUserService().
				createLogoutURL(destinationURL):"/system/signout";
	}
	public static Station get(HttpServletRequest req){
		getAll(req);
		return (Station)req.getAttribute(ATR);	
	}
	public static User getCurrentUser(HttpServletRequest req){
		User r=null;
		if(ggl){
			if(UserServiceFactory.getUserService().isUserLoggedIn()){
				r=new User();
				((User)r).google(UserServiceFactory.getUserService());
			}
		}else try{
			getAll(req);
			Station s=Station.get(req);
			if(s!=null)
				r=new User().update(s.getOwnerId());
		}catch(MsgException e){
			//e.printStackTrace();
		}
		return r;
	}

	protected Session ssn;

	public Station(){
		atr=idx=ATR;
	}
	public void addTo(HttpServletResponse resp){
		try{
			prepSession();
			ssn.commit();
			resp.setHeader("Set-Cookie",this+"; HttpOnly");
		}catch(MsgException e){
			e.printStackTrace();
		}
	}
	public Session getSession(){
		return ssn;
	}
	public Item getOwner()throws MsgException{
		return ssn==null?null:ssn.getOwner();
	}
	public long getOwnerId(){
		return ssn==null?0:ssn.getOwnerId();
	}
	public long getTime(){
		return ssn==null?0:ssn.getTime();
	}
	public boolean isOwnerSame(Asset asset){
		return ssn==null?false:ssn.isOwnerSame(asset);
	}
	protected void prepSession(){
		if(ssn==null)
			ssn=new Session();
	}
	public void setOwner(Individual owner){
		prepSession();
		if(owner==null)
			ssn.setOwner(0);
		else ssn.setOwner(owner);
	}
	public String toString(){
		long x=3600000L*24*3652;	// 10 years
		Date d=new Date();
		d.setTime(d.getTime()+x);
		return idx+'='+ssn.getPermaLink()+"; path=/; expires="+toGMTString(d);
	}
	@Override
	public void set(HttpServletRequest req,Cookie cookie)throws MsgException{
		super.set(req,cookie);
		ssn=new Session();
		ssn.setPermaLink(cookie.getValue());
		ssn.update();
	}
}